package com.mspbots.core.wise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.wise.mapper.TenantExceptionLogMapper;
import com.mspbots.core.wise.mapper.TenantUserMapper;
import com.mspbots.core.wise.mapper.UsersMapper;
import com.mspbots.core.wise.model.TenantExceptionLog;
import com.mspbots.core.wise.model.TenantUser;
import com.mspbots.core.wise.model.Users;
import com.mspbots.core.wise.service.UsersService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * com.mspbots.core.wise.service.impl.UsersServiceImpl
 *
 * @author Jason
 * @date 2020/3/23
 **/
@Slf4j
@Service
@AllArgsConstructor
public class UsersServiceImpl extends AbstractBaseServiceImpl<UsersMapper, Users> implements UsersService {

    private final TenantUserMapper tenantUserMapper;
    private final TenantExceptionLogMapper tenantExceptionLogMapper;

    @Override
    public Boolean disableUserNoCw(Users user) {
        Boolean flag = false;
        QueryWrapper<TenantUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", user.getTenantId());
        Integer count = tenantUserMapper.selectCount(queryWrapper);
        if (count == 0) {
            flag = false;
        } else {
            List<Users> users = this.baseMapper.selectDisableUserNoCw(user.getTenantId());
            if (!CollectionUtils.isEmpty(users)) {
                String userIds = getUserIds(users);
                flag = this.baseMapper.updateDisableUserNoCw(user.getTenantId(), userIds) >= 0;

                if (flag) {
                    for (Users u : users) {
                        TenantExceptionLog log = new TenantExceptionLog();
                        log.setTenantId(user.getTenantId());
                        log.setName("Users");
                        log.setType("USERS-DISABLE");
                        log.setStatus(200);
                        log.setMsg("disable user " + u.getUsername() + "[" + u.getId() + "]" + " By " + user.getUsername() + "[" + user.getId() + "]");
                        this.tenantExceptionLogMapper.insert(log);
                    }
                }
            }
        }
        return flag;
    }


    private String getUserIds(List<Users> users) {
        String result = "";
        if (users.size() == 1) {
            return users.get(0).getId() + "";
        }
        for (int i = 0; i < users.size(); i++) {

            if (i == users.size() - 1) {
                result = result + users.get(i).getId();
            } else {
                result = result + users.get(i).getId() + ",";
            }

        }
        return result;
    }
}
